package com.sicau.smarttraceplatform.config.security;

import com.sicau.smarttraceplatform.entity.User;
import com.sicau.smarttraceplatform.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static com.sicau.smarttraceplatform.common.constants.commonConstants.CURRENT_USER;

public class JWTAuthenticationFilter extends GenericFilterBean {


    private static final String HEADER_STRING = "Authorization";

    private static final String TOKEN_PREFIX = "Bearer";

    private UserDetailsService userDetailsService;


    @SuppressWarnings("WeakerAccess")
    public JWTAuthenticationFilter(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader(HEADER_STRING);
        if (StringUtils.isNotBlank(token)  && token.startsWith(TOKEN_PREFIX)) {
            Claims claims = JwtUtil.verifyToken(token.replace(TOKEN_PREFIX, ""));
            if (claims != null) {
                User user = (User) userDetailsService.loadUserByUsername(claims.getSubject());
                SecurityContextHolder.getContext().setAuthentication(new JWTAuthenticationToken(user, user.getPassword(), user.getAuthorities()));
                req.getSession().setAttribute(CURRENT_USER, user);
            }
        }
        filterChain.doFilter(req, response);
    }

}
